package com.lishuang.system.service.impl;

import com.lishuang.basic.service.impl.BaseServiceImpl;
import com.lishuang.system.domain.Role;
import com.lishuang.system.mapper.RoleMapper;
import com.lishuang.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {


    @Autowired
    private RoleMapper roleMapper;

    /**
     * 添加
     *
     * @param role
     */
    @Override
    @Transactional
    public void save(Role role) {
        super.save(role);
        add(role);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    @Transactional
    public void remove(Long id) {
        roleMapper.removeRoleMenus(id);
        roleMapper.removeRolePermissons(id);
        roleMapper.removeEmployeeRole(id);
        super.remove(id);
    }

    /**
     * 修改
     *
     * @param role
     */
    @Override
    @Transactional
    public void update(Role role) {
        roleMapper.removeRoleMenus(role.getId());
        roleMapper.removeRolePermissons(role.getId());
        add(role);
        super.update(role);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        for (Long id : ids) {
            remove(id);
        }
    }

    /**
     * 抽取保存公共代码
     *
     * @param role
     */
    private void add(Role role) {
        List<Long> menus = role.getMenus();
        List<Long> permissions = role.getPermissions();
        if (menus.size() > 0) {
            roleMapper.saveRoleMenus(role.getId(), menus);
        }
        if (permissions.size() > 0) {
            roleMapper.saveRolePermissons(role.getId(), permissions);
        }
    }
}
